var express = require('express');
var router = express.Router();
var db = require('../public/javascripts/db');
var async = require('async');
var token = require('../public/javascripts/utils');

router.get('/', (req, res) => {
    var sql = "SELECT * FROM tasks WHERE status = ? AND user_id = ?";
    var sqlParams = [0, token.verifyToken(req.headers.token)]
    db.query(sql, sqlParams, (err, result) => {
        if (err) {
            throw err;
            return;
        } else {
            console.log('status result', result);
            async.map(result, function (data, callback) {
                    var sql2 = "SELECT * FROM images WHERE id = ?";
                    db.query(sql2, data.img_id, (err2, result2) => {
                        if (err2) {
                            throw err2;
                            return;
                        } else {
                            data['image'] = result2[0].location;
                            data['time'] = result2[0].load_time;
                            data['mode'] = result2[0].type;
                            data['image_id'] = result2[0].id;
                            data['medical_num'] = result2[0].medical_num;

                            var sql3 = "SELECT * FROM users WHERE id = ?";
                            db.query(sql3, data.owner_id, (err3, result3) => {
                                if (err3) {
                                    throw err3;
                                    return;
                                } else {
                                    data['birth_place'] = result3[0].birth_place;
                                    data['birth_date'] = result3[0].birth_date;
                                    data['identify_num'] = result3[0].identify_num;
                                    data['name'] = result3[0].name;
                                    data['gender'] = result3[0].gender;
                                    data['telephone'] = result3[0].phone;
                                    data['medical_history'] = result3[0].medical_history;
                                    callback(null, data);
                                }
                            })
                        }
                    })
                }
                , function (err, finaldata) {
                    console.log('finaldata', finaldata);
                    res.send({data: finaldata});
                })
        }
    })
})

module.exports = router;